﻿using System.Collections;
using System.Collections.Generic;
using UnityEngine;
namespace JumpBall_2
{
    public class BlockSpawn : MonoBehaviour
    {
        public readonly int BlockNumber = 16;           //方块数量
        public GameObject blockPrefab;                  //方块预制件
        public float moveSpeed;                         //移动速度

        private List<Transform> blockList;              //存储方块的数字列表

        public void Awake()
        {

            blockList = new List<Transform>();
            InitBlock();
        }
        void Start()
        {

        }

        // Update is called once per frame
        private void FixedUpdate()
        {
            if (GameManager.Instance.gameState != GameState.Start)
            {
                return;
            }
            foreach (Transform trans in blockList)
            {
                trans.Translate(new Vector3(-moveSpeed * Time.deltaTime, 0, 0));
            }
        }

        //生成方块
        public void InitBlock()
        {
            for (int i = 0; i < BlockNumber; i++)
            {
                GameObject block = Instantiate(blockPrefab);
                if (block == null)
                {
                    return;
                }
                block.transform.SetParent(this.transform);
                block.transform.position = new Vector3(i * 2, 0, 0);
                //一开始生成几个安全方块
                if (i < 3)
                {
                    Vector3 scale = block.transform.localScale;
                    scale.x = 2;
                    block.transform.localScale = scale;
                }
                else
                {
                    ResetBlock(block.transform);
                }

                //添加数组元素
                blockList.Add(block.transform);
            }
        }

        //方块坐标和缩放调整
        public void ResetBlock(Transform block)
        {
            //随机修改缩放
            Vector3 scale = block.localScale;
            scale.x = Random.Range(0.5f, 1.0f);
            block.localScale = scale;

            //随机修改坐标
            Vector3 position = block.position;
            position.y = Random.Range(-0.5f, 0.5f);
            block.position = position;
        }

        //重置方块位置
        public void Respawn()
        {
            //最后一个位置上的方块
            Transform last = blockList[blockList.Count - 1];
            //第一个方块
            Transform first = blockList[0];

            Vector3 position = last.position;
            position.x += 2;
            first.position = position;

            //数组进行一次位置交换
            blockList.RemoveAt(0);
            ResetBlock(first);
            blockList.Add(first);
        }

        private void OnTriggerEnter(Collider other)
        {
            if (other.tag == "Respawn")
            {
                Respawn();
            }
        }
    }
}
